package com.imooc.exception;

import com.imooc.grance.result.GraceJsonResult;
import com.imooc.grance.result.ResponseStatusEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/14/14:24
 * @Description:
 * 统一异常拦截处理
 * 可以针对异常类型进行捕获，然后以JSON格式返回给前端
 */
@ControllerAdvice
public class GraceExceptionHandler {
    /**
     * 处理自定义的业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomerException.class)
    @ResponseBody
    public GraceJsonResult returnMyException(CustomerException e) {
        e.printStackTrace();
        return GraceJsonResult.exception(e.getResponseStatusEnum());
    }


    /**
     * 处理系统的MaxUploadSizeExceededException异常
     * @param e
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public GraceJsonResult returnMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        e.printStackTrace();
        return GraceJsonResult.errorCustom(ResponseStatusEnum.FILE_MAX_SIZE_ERROR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJsonResult returnException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> errors = getErrors(result);

        return GraceJsonResult.errorMap(errors);
    }

    /**
     * 校验有没有错误的方法
     * @param result
     * @return
     */
    private Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
//        List<ObjectError> errorList = result.getAllErrors();
        //获取所有的错误信息的列表
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            String fieldName = error.getField();
            String message = error.getDefaultMessage();
            map.put(fieldName, message);
        }
        return map;
    }
}
